<?php

class Quest_captcha
{
	private $ci;
	
	public function __construct()
	{
		$this->ci =& get_instance();
		$this->_init();
	}
	
	private function _init($reset = FALSE)
	{
		if($this->ci->session->userdata('questcap') == FALSE OR $reset == TRUE)
		{
			$questions = $this->generate_question();
			$question_key = array_rand($questions);
			$selected = $questions[$question_key];
			
			$for_session = [
				'question_k'=> $question_key,
				'question' 	=> $selected[0],
				'answer'	=> $selected[1],
				'questcap'	=> TRUE
			];
			
			$this->ci->session->set_userdata($for_session);
		}
	}
	
	private function generate_question()
	{
		$question[]=['2 + 2 = ?',4]; 
		$question[]=['First letter of the English Alphabet?','a']; 
		$question[]=['8 x 2',16]; 
		$question[]=['Third letter of the English Alphabet?','c']; 
		$question[]=['10 + 10 = ?',20]; 
		$question[]=['6 + 6 = ?',12]; 
		$question[]=['5 + 1 = ?',6];  
		$question[]=['3 + 2 = ?',5];  
		$question[]=['8 + 7 = ?',15];  
		$question[]=['6 - 3 = ?',3];  
		$question[]=['1 X 1 = ?',1];
		$question[]=['fill in missing letter( C_MPUTER )','o'];
		$question[]=['fill in missing letter( INT_RN_T)','e'];
		$question[]=['fill in missing letter( CE_L P_ONE )','lp'];
		$question[]=['fill in missing letter( CAM_RA )','e'];
		$question[]=['fill in missing letter( T__TH BRUSS )','oo'];
		$question[]=['fill in missing letter( AIR PL_NE )','a'];
		$question[]=['2 + 4 + 1 = ?',7];
		$question[]=['8 + 1 - 1 = ?',8];
		$question[]=['3 - 1 + 1 = ?',3];
	
		return $question;
	}
	
	// PUBLICS
	
	public function get_question()
	{
		return $this->ci->session->userdata('question');
	}
	
	public function check_answer($answer)
	{
		return strtolower($this->ci->session->userdata('answer')) == trim(strtolower($answer));
	}
	
	public function reset_question()
	{
		$this->_init(TRUE);
	}
}